<template>
  <div class="container">
    <Breadcrumb :items="['menu.problem', 'menu.problem.info']"/>
    <a-card class="general-card" :title="$t('menu.problem.info')">
      <a-row>
        <a-col :flex="1">
          <a-form :model="formModel" :label-col-props="{ span: 6 }" :wrapper-col-props="{ span: 18 }"
                  label-align="left">
            <a-row :gutter="16">
              <a-col :span="8">
                <a-form-item field="title" :label="$t('problem.info.form.title')">
                  <a-input v-model="formModel.title"
                           :placeholder="$t('problem.info.form.title.placeholder')"/>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="difficulty" :label="$t('problem.info.form.difficulty')">
                  <a-select v-model="formModel.difficulty" :options="difficultyOptions"/>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="16">
              <a-col :span="8">
                <a-form-item field="tagIds" :label="$t('problem.info.form.tagIds')">
                  <a-button type="primary"
                            @click="selectHandleClick()">{{ $t('problem.info.form.tagIds.do') }}
                  </a-button>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="isPrecise" :label="$t('problem.info.form.isPrecise')">
                  <a-radio-group v-model="formModel.isPrecise">
                    <a-radio :value="1">普通查找</a-radio>
                    <a-radio :value="2">精确查找</a-radio>
                  </a-radio-group>
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </a-col>
        <a-divider style="height: 84px" direction="vertical"/>
        <a-col :flex="'86px'" style="text-align: right">
          <a-space direction="vertical" :size="18">
            <a-button type="primary" @click="search">
              <template #icon>
                <icon-search/>
              </template>
              {{ $t('searchTable.form.search') }}
            </a-button>
            <a-button @click="reset">
              <template #icon>
                <icon-refresh/>
              </template>
              {{ $t('searchTable.form.reset') }}
            </a-button>
          </a-space>
        </a-col>
      </a-row>
      <a-divider style="margin-top: 0"/>
      <a-row style="margin-bottom: 16px">
        <a-col :span="12">
          <a-space>
            <a-button type="primary" @click="addHandleClick">
              <template #icon>
                <icon-plus/>
              </template>
              {{ $t('searchTable.operation.create') }}
            </a-button>
          </a-space>
        </a-col>
        <a-col :span="12" style="display: flex; align-items: center; justify-content: end">
          <a-tooltip :content="$t('searchTable.actions.columnSetting')">
            <a-popover trigger="click" position="bl" @popup-visible-change="popupVisibleChange">
              <div class="action-icon">
                <icon-settings size="18"/>
              </div>
              <template #content>
                <div id="tableSetting">
                  <div v-for="(item, index) in showColumns" :key="item.dataIndex" class="setting">
                    <div style="margin-right: 4px; cursor: move">
                      <icon-drag-arrow/>
                    </div>
                    <div>
                      <a-checkbox v-model="item.checked" @change="
		                  handleChange($event, item as TableColumnData, index)
		                ">
                      </a-checkbox>
                    </div>
                    <div class="title">
                      {{ item.title === '#' ? '序列号' : item.title }}
                    </div>
                  </div>
                </div>
              </template>
            </a-popover>
          </a-tooltip>
          <a-tooltip :content="$t('searchTable.actions.refresh')">
            <div class="action-icon" @click="search">
              <icon-refresh size="18"/>
            </div>
          </a-tooltip>
          <a-dropdown @select="handleSelectDensity">
            <a-tooltip :content="$t('searchTable.actions.density')">
              <div class="action-icon">
                <icon-line-height size="18"/>
              </div>
            </a-tooltip>
            <template #content>
              <a-doption v-for="item in densityList" :key="item.value" :value="item.value"
                         :class="{ active: item.value === size }">
                <span>{{ item.name }}</span>
              </a-doption>
            </template>
          </a-dropdown>
        </a-col>
      </a-row>
      <a-table row-key="index" :loading="loading" :pagination="pagination"
               :columns="(cloneColumns as TableColumnData[])" :data="renderData.items" :bordered="false" :size="size"
               @page-change="onPageChange">
        <template #difficulty="{ record }">
          <a-tag v-if="record.difficulty==1" color="green">{{ t('problem.info.form.difficulty.easy') }}</a-tag>
          <a-tag v-if="record.difficulty==2" color="gold">{{ t('problem.info.form.difficulty.mid') }}</a-tag>
          <a-tag v-if="record.difficulty==3" color="red">{{ t('problem.info.form.difficulty.difficult') }}</a-tag>
        </template>
        <template #isPublic="{ record }">
          <div>
            {{ record.isPublic == 1 ? t('problem.info.columns.isPublic.is') : t('problem.info.columns.isPublic.not') }}
          </div>
        </template>
        <template #operations="{record}">
          <a-button type="text" size="small" @click="updateHandleClick(record)">
            {{ $t('searchTable.columns.operations.update') }}
          </a-button>
          <a-button type="text" size="small" @click="updateSampleHandleClick(record)">
            {{ $t('problem.info.operations.sample') }}
          </a-button>
        </template>
      </a-table>
    </a-card>
    <a-modal width="700px" v-model:visible="selectTagVisable" title="选择题目标签" @cancel="selectHandleCancel"
             @before-ok="selectHandleBeforeOk">
      <div style="height: 600px;width: 600px;">
        <div v-for="(item,index) in tagTree" :key="index">
          <div style="padding-bottom: 20px;">
            <div style="line-height: 5px;">
              <div style="font-size: 20px;">{{ item.name }}</div>
              <a-divider/>
            </div>
            <a-checkbox-group v-model="formModel.tagIds">
              <a-checkbox v-for="(child,index) in item.children" :key="index"
                          :value="child.id">{{ child.name }}
              </a-checkbox>
            </a-checkbox-group>
          </div>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import {computed, ref, reactive, watch, nextTick} from 'vue';
import {useI18n} from 'vue-i18n';
import useLoading from '@/hooks/loading';
import {useRouter} from 'vue-router';
import {TagTreeShowVo, searchInfoByPage, getTagTree} from '@/api/problem';
import {PageParams, generatePageResult} from '@/types/page';
import {Pagination} from '@/types/global';
import type {SelectOptionData} from '@arco-design/web-vue/es/select/interface';
import type {TableColumnData} from '@arco-design/web-vue/es/table/interface';
import cloneDeep from 'lodash/cloneDeep';
import Sortable from 'sortablejs';

type SizeProps = 'mini' | 'small' | 'medium' | 'large';
type Column = TableColumnData & { checked?: true };

const addVisible = ref(false);
const selectTagVisable = ref(false);
const router = useRouter();

const generateFormModel = () => {
  return {
    difficulty: 0,
    isPrecise: 1,
    tagIds: [],
    title: ""
  };
};
const {loading, setLoading} = useLoading(true);
const {t} = useI18n();
const renderData = ref(generatePageResult());
const formModel = ref(generateFormModel());
const cloneColumns = ref<Column[]>([]);
const showColumns = ref<Column[]>([]);
const tagTree = ref<TagTreeShowVo[]>(new Array(7).fill({}));


const size = ref<SizeProps>('medium');

const basePagination: Pagination = {
  current: 1,
  pageSize: 30,
};
const pagination = reactive({
  ...basePagination,
});
const addHandleClick = () => {
  router.push({
    name: 'CreateProblem',
  });
};
const selectHandleClick = () => {
  selectTagVisable.value = true
};
const updateHandleClick = (record: any) => {
  router.push({
    name: 'UpdateProblem',
    query: {problemId: record.id}
  });
};
const updateSampleHandleClick = (record: any) => {
  router.push({
    name: 'ProblemSample',
    query: {problemId: record.id}
  });
};
const selectHandleCancel = () => {
  selectTagVisable.value = false;
  formModel.value.tagIds = []
};
const selectHandleBeforeOk = (done) => {
  done();
  selectTagVisable.value = false;
};
const densityList = computed(() => [
  {
    name: t('searchTable.size.mini'),
    value: 'mini',
  },
  {
    name: t('searchTable.size.small'),
    value: 'small',
  },
  {
    name: t('searchTable.size.medium'),
    value: 'medium',
  },
  {
    name: t('searchTable.size.large'),
    value: 'large',
  },
]);
const columns = computed<TableColumnData[]>(() => [
  {
    title: t('problem.info.columns.id'),
    dataIndex: 'id',
    slotName: 'id',
  },
  {
    title: t('problem.info.columns.title'),
    dataIndex: 'title',
    slotName: 'title',
  },
  {
    title: t('problem.info.columns.difficulty'),
    dataIndex: 'difficulty',
    slotName: 'difficulty',
  },
  {
    title: t('problem.info.columns.commitCount'),
    dataIndex: 'commitCount',
    slotName: 'commitCount',
  },
  {
    title: t('problem.info.columns.correctCount'),
    dataIndex: 'correctCount',
    slotName: 'correctCount',
  },
  {
    title: t('problem.info.columns.isPublic'),
    dataIndex: 'isPublic',
    slotName: 'isPublic',
  },
  {
    title: t('problem.info.columns.updateTime'),
    dataIndex: 'updateTime',
    slotName: 'updateTime',
  }, {
    title: t('searchTable.columns.operations'),
    dataIndex: 'operations',
    slotName: 'operations',
  }
]);
const difficultyOptions = computed<SelectOptionData[]>(() => [
  {
    label: t('problem.info.form.difficulty.all'),
    value: 0,
  },
  {
    label: t('problem.info.form.difficulty.easy'),
    value: 1,
  },
  {
    label: t('problem.info.form.difficulty.mid'),
    value: 2,
  },
  {
    label: t('problem.info.form.difficulty.difficult'),
    value: 3,
  }
]);
const getTreeTagList = async () => {
  try {
    const {data} = await getTagTree();
    tagTree.value = data;
  } catch (err) {
    // you can report use errorHandler or other
  } finally {
    setLoading(false);
  }
}
getTreeTagList();
const fetchData = async (
    params: PageParams = {current: 1, pageSize: 30},
) => {
  setLoading(true);
  try {
    const {data} = await searchInfoByPage(params, {
      difficulty: formModel.value.difficulty,
      isPrecise: formModel.value.isPrecise,
      tagIds: formModel.value.tagIds,
      title: formModel.value.title
    });
    renderData.value.items = data.items;
    pagination.current = params.current;
    pagination.total = data.counts;
  } catch (err) {
    // you can report use errorHandler or other
  } finally {
    setLoading(false);
  }
};

const search = () => {
  fetchData({
    ...basePagination,
    ...formModel.value,
  } as unknown as PageParams);
};
const onPageChange = (current: number) => {
  fetchData({...basePagination, current});
};

fetchData();
const reset = () => {
  formModel.value = generateFormModel();
};

const handleSelectDensity = (
    val: string | number | Record<string, any> | undefined,
    e: Event
) => {
  size.value = val as SizeProps;
};

const handleChange = (
    checked: boolean | (string | boolean | number)[],
    column: Column,
    index: number
) => {
  if (!checked) {
    cloneColumns.value = showColumns.value.filter(
        (item) => item.dataIndex !== column.dataIndex
    );
  } else {
    cloneColumns.value.splice(index, 0, column);
  }
};

const exchangeArray = <T extends Array<any>>(
    array: T,
    beforeIdx: number,
    newIdx: number,
    isDeep = false
): T => {
  const newArray = isDeep ? cloneDeep(array) : array;
  if (beforeIdx > -1 && newIdx > -1) {
    // 先替换后面的，然后拿到替换的结果替换前面的
    newArray.splice(
        beforeIdx,
        1,
        newArray.splice(newIdx, 1, newArray[beforeIdx]).pop()
    );
  }
  return newArray;
};

const popupVisibleChange = (val: boolean) => {
  if (val) {
    nextTick(() => {
      const el = document.getElementById('tableSetting') as HTMLElement;
      const sortable = new Sortable(el, {
        onEnd(e: any) {
          const {oldIndex, newIndex} = e;
          exchangeArray(cloneColumns.value, oldIndex, newIndex);
          exchangeArray(showColumns.value, oldIndex, newIndex);
        },
      });
    });
  }
};

watch(
    () => columns.value,
    (val) => {
      cloneColumns.value = cloneDeep(val);
      cloneColumns.value.forEach((item, index) => {
        item.checked = true;
      });
      showColumns.value = cloneDeep(cloneColumns.value);
    },
    {deep: true, immediate: true}
);
</script>

<script lang="ts">
export default {
  name: 'ProblemInfo',
};
</script>

<style scoped lang="less">
.container {
  padding: 0 20px 20px 20px;
}

:deep(.arco-table-th) {
  &:last-child {
    .arco-table-th-item-title {
      margin-left: 16px;
    }
  }
}

.action-icon {
  margin-left: 12px;
  cursor: pointer;
}

.active {
  color: #0960bd;
  background-color: #e3f4fc;
}

.setting {
  display: flex;
  align-items: center;
  width: 200px;

  .title {
    margin-left: 12px;
    cursor: pointer;
  }
}
</style>